<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { playlistManageAPI, PlaylistVO } from "@/services/songList";
import { musicManageAPI, MusicVO } from "@/services/song";
import { debounce } from "lodash-es";
import { ElMessage, ElMessageBox } from "element-plus";

// 歌单数据
const playlistData = ref<PlaylistVO[]>([]);
// 歌曲数据缓存
const musicDataCache = ref<Record<string, MusicVO[]>>({});
const expandedRowId = ref<string | null>(null);
// 所有歌曲数据（用于添加歌曲到歌单）
const allMusicData = ref<MusicVO[]>([]);
// 添加歌曲对话框控制
const showAddMusicDialog = ref(false);
// 当前选择的歌单ID
const currentPlaylistId = ref("");
// 选择的歌曲ID
const selectedMusicId = ref("");

const query = ref({ name: "" });
const size = ref("15");
const options = [
  { value: "15", label: "15" },
  { value: "20", label: "20" },
  { value: "30", label: "30" },
  { value: "40", label: "40" },
  { value: "50", label: "50" },
];

const currentPage = ref(1);
const total = ref(0);
const loading = ref(false);
const musicTypeMap = ref<Record<number, string>>({});

// 获取可添加的歌曲列表（排除已在歌单中的歌曲）
const getAvailableMusic = computed(() => {
  if (!currentPlaylistId.value || !allMusicData.value.length) return allMusicData.value;
  
  const currentPlaylistMusicIds = musicDataCache.value[currentPlaylistId.value]?.map(m => m.id) || [];
  return allMusicData.value.filter(music => 
    !currentPlaylistMusicIds.includes(music.id)
  );
});

// 获取所有歌曲
const getAllMusic = async () => {
  try {
    const response = await musicManageAPI().getMusicByName("", 1, 1000);
    allMusicData.value = response.data.items.filter(item => item !== null);
  } catch (error) {
    ElMessage.error("获取歌曲列表失败");
  }
};

// 添加歌曲到歌单
const handleAddMusicToPlaylist = async () => {
  if (!selectedMusicId.value) {
    ElMessage.warning("请选择一首歌曲");
    return;
  }

  try {
    await playlistManageAPI().addMusicToPlaylist(
      currentPlaylistId.value,
      selectedMusicId.value
    );
    ElMessage.success("添加歌曲成功");
    showAddMusicDialog.value = false;
    // 刷新当前歌单的歌曲列表
    if (musicDataCache.value[currentPlaylistId.value]) {
      const addedMusic = allMusicData.value.find(
        music => music.id === selectedMusicId.value
      );
      if (addedMusic) {
        musicDataCache.value[currentPlaylistId.value].push(addedMusic);
      }
    }
    selectedMusicId.value = "";
  } catch (error) {
    ElMessage.error("添加歌曲失败");
  }
};

// 打开添加歌曲对话框
const openAddMusicDialog = async (playlistId: string) => {
  currentPlaylistId.value = playlistId;
  selectedMusicId.value = "";
  
  // 确保已加载该歌单的歌曲列表
  if (!musicDataCache.value[playlistId]) {
    await loadMusicData(playlistId);
  }
  
  showAddMusicDialog.value = true;
};

// 获取歌曲类型
const getMusicTypes = async () => {
  try {
    const res = await musicManageAPI().getmusicType();
    const map: Record<number, string> = {};
    res.data.forEach((type: { id: number; typeName: string }) => {
      map[type.id] = type.typeName;
    });
    musicTypeMap.value = map;
  } catch (error) {
    ElMessage.error("获取歌曲类型失败");
  }
};

// Dialog controls
const showAddDialog = ref(false);
const formData = ref<PlaylistVO>({
  id: "",
  name: "",
  description: "",
  userId: null,
  musicIds: null,
  category: null,
  createTime: null,
  updateTime: null,
  isPublic: 0, // 默认私有
});

// 分页数据
const paginatedTableData = computed(() => playlistData.value);

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getData();
};

const handleSizeChange = (val: string) => {
  size.value = val;
  currentPage.value = 1;
  getData();
};

const handleEdit = (row: PlaylistVO) => {
  formData.value = { ...row };
  showAddDialog.value = true;
};

const handleAdd = () => {
  formData.value = {
    id: "",
    name: "",
    description: "",
    userId: null,
    musicIds: null,
    category: null,
    createTime: null,
    updateTime: null,
    isPublic: 0,
  };
  showAddDialog.value = true;
};

const handleDelete = async (row: PlaylistVO) => {
  try {
    await ElMessageBox.confirm("确定要删除该歌单吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await playlistManageAPI().deletePlaylist(row.id);
    ElMessage.success("删除成功");
    getData();
  } catch (error) {
    if (error !== "cancel") ElMessage.error("删除失败");
  }
};

const handleRemoveMusic = async (playlistId: string, musicId: string) => {
  try {
    await ElMessageBox.confirm("确定要从歌单中移除该歌曲吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await playlistManageAPI().removeMusicFromPlaylist(playlistId, musicId);
    ElMessage.success("移除成功");
    if (musicDataCache.value[playlistId]) {
      musicDataCache.value[playlistId] = musicDataCache.value[playlistId].filter(
        (music) => music.id !== musicId
      );
    }
  } catch (error) {
    if (error !== "cancel") ElMessage.error("移除失败");
  }
};

const loadMusicData = async (playlistId: string) => {
  if (musicDataCache.value[playlistId]) return musicDataCache.value[playlistId];
  try {
    const response = await playlistManageAPI().getPlaylistMusics(playlistId);
    const validMusicData = response.data
      .filter((item) => item !== null)
      .map((item) => ({
        id: item.id,
        musicId: item.musicId,
        musicCoverUrl: item.musicCoverUrl || "",
        musicName: item.musicName || "未知",
        musicAuthor: item.musicAuthor || "未知",
        musicAlbum: item.musicAlbum || "未知",
        musicLength: item.musicLength || "未知",
        musicTypeId: item.musicTypeId || null,
        status: item.status || "0",
      }));
    musicDataCache.value[playlistId] = validMusicData;
    return validMusicData;
  } catch (error) {
    ElMessage.error("获取歌曲数据失败");
    return [];
  }
};

const onExpandChange = async (row: PlaylistVO, expanded: boolean) => {
  if (expanded) {
    expandedRowId.value = row.id;
    await loadMusicData(row.id);
  } else {
    if (expandedRowId.value === row.id) expandedRowId.value = null;
  }
};

const isRowExpanded = (row: PlaylistVO) => expandedRowId.value === row.id;

const submitForm = async () => {
  try {
    if (formData.value.id) {
      await playlistManageAPI().updatePlaylist(formData.value);
      ElMessage.success("更新成功");
    } else {
      await playlistManageAPI().addPlaylist(formData.value);
      ElMessage.success("添加成功");
    }
    showAddDialog.value = false;
    getData();
  } catch (error) {
    ElMessage.error("操作失败");
  }
};

const handleSearch = debounce(() => {
  currentPage.value = 1;
  getData();
}, 500);

onMounted(() => {
  getMusicTypes();
  getData();
  getAllMusic();
});

watch(() => query.value.name, () => handleSearch());

const getData = async () => {
  try {
    loading.value = true;
    const response = await playlistManageAPI().getPlaylists();
    playlistData.value = response.data;
    total.value = response.data.total || playlistData.value.length;
  } catch (error) {
    ElMessage.error("获取歌单失败");
  } finally {
    loading.value = false;
  }
};

// Helper functions for rendering
const formatDate = (dateString: string | null) => {
  return dateString ? new Date(dateString).toLocaleDateString() : "未知";
};

const getMusicCount = (musicIds: string[] | null) => {
  return musicIds ? musicIds.length : 0;
};

const getPublicStatus = (isPublic: number) => {
  return isPublic === 1 ? "公开" : "私有";
};
</script>
<template>
  <div class="flex h-full gap-6">
    <div
      class="flex-1 bg-white rounded-lg p-4 flex flex-col justify-between min-w-0"
    >
      <div class="flex items-center justify-between gap-8 mb-4 flex-wrap">
        <div class="flex gap-8 flex-wrap"></div>
        <el-button type="primary" @click="handleAdd">
          <span>添加歌单</span>
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="paginatedTableData"
        style="width: 100%"
        height="85%"
        header-row-class-name="table-header"
        cell-class-name="table-cell"
        @expand-change="onExpandChange"
        :row-key="(row) => row.id"
        :expand-row-keys="[expandedRowId]"
      >
        <!-- 展开行显示歌曲详情 -->
        <el-table-column type="expand">
          <template #default="props">
            <div>
              <el-table
                :data="musicDataCache[props.row.id] || []"
                v-loading="!musicDataCache[props.row.id]"
                style="width: 100%"
              >
                <el-table-column label="歌曲封面" align="center">
                  <template #default="scope">
                    <el-image
                      v-if="scope.row?.musicCoverUrl"
                      :src="scope.row.musicCoverUrl"
                      style="width: 60px; height: 60px"
                      fit="cover"
                    />
                    <span v-else>无封面</span>
                  </template>
                </el-table-column>
                <el-table-column label="歌曲名称">
                  <template #default="scope">
                    {{ scope.row?.musicName || "未知" }}
                  </template>
                </el-table-column>
                <el-table-column label="歌手">
                  <template #default="scope">
                    {{ scope.row?.musicAuthor || "未知" }}
                  </template>
                </el-table-column>
                <el-table-column label="类型" align="center">
                  <template #default="scope">
                    {{ musicTypeMap[scope.row.musicTypeId] || "未知类型" }}
                  </template>
                </el-table-column>
                <el-table-column label="时长" align="center">
                  <template #default="scope">
                    {{ scope.row?.musicLength || "未知" }}
                  </template>
                </el-table-column>
                <el-table-column label="状态">
                  <template #default="scope">
                    <el-tag
                      :type="scope.row?.status === '1' ? 'success' : 'danger'"
                    >
                      {{ scope.row?.status === "1" ? "上架" : "下架" }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="120">
                  <template #default="scope">
                    <el-button
                      type="danger"
                      size="small"
                      @click="handleRemoveMusic(props.row.id, scope.row.id)"
                    >
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="name"
          label="歌单名"
          align="center"
          width="180"
        />
        <el-table-column label="描述" align="center">
          <template #default="scope">
            {{ scope.row.description || "无" }}
          </template>
        </el-table-column>
        <el-table-column label="分类" align="center" width="120">
          <template #default="scope">
            {{ scope.row.category || "未分类" }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isPublic === 1 ? 'success' : 'info'">
              {{ getPublicStatus(scope.row.isPublic) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="240">
          <template #default="scope">
            <div class="flex justify-center gap-4">
              <el-button
                size="small"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="success"
                @click="openAddMusicDialog(scope.row.id)"
              >
                添加歌曲
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="h-[36px] flex items-center justify-between mt-6">
        <div>
          <span class="text-[#8a8a8f] text-sm mr-2">每页结果</span>
          <el-select
            v-model="size"
            placeholder="Select"
            style="width: 70px"
            class="input-grey"
            @change="handleSizeChange"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <el-pagination
          background
          class="justify-items-end"
          layout="prev, pager, next"
          :total="total"
          :page-size="parseInt(size)"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 添加/编辑歌单对话框 -->
  <el-dialog
    v-model="showAddDialog"
    :title="formData.id ? '编辑歌单' : '添加歌单'"
    width="50%"
  >
    <el-form :model="formData" label-width="100px">
      <el-form-item label="歌单名" required>
        <el-input v-model="formData.name" placeholder="请输入歌单名" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="formData.description" placeholder="请输入描述" />
      </el-form-item>
      <el-form-item label="分类">
        <el-input v-model="formData.category" placeholder="请输入分类" />
      </el-form-item>
      <el-form-item label="公开状态">
        <el-select v-model="formData.isPublic" placeholder="请选择公开状态">
          <el-option label="公开" :value="1" />
          <el-option label="私有" :value="0" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showAddDialog = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>

<!-- 添加歌曲到歌单对话框 -->
<el-dialog
  v-model="showAddMusicDialog"
  title="添加歌曲到歌单"
  width="60%"
>
  <el-table
    :data="getAvailableMusic"
    style="width: 100%"
    height="400"
    @row-click="(row) => selectedMusicId = row.id"
  >
    <el-table-column width="50">
      <template #default="scope">
        <el-radio v-model="selectedMusicId" :label="scope.row.id" />
      </template>
    </el-table-column>
    <el-table-column label="歌曲封面" width="120">
      <template #default="scope">
        <el-image
          v-if="scope.row.musicCoverUrl"
          :src="scope.row.musicCoverUrl"
          style="width: 60px; height: 60px"
          fit="cover"
        />
        <span v-else>无封面</span>
      </template>
    </el-table-column>
    <el-table-column prop="musicName" label="歌曲名称" />
    <el-table-column prop="musicAuthor" label="歌手" width="150" />
    <el-table-column label="类型" width="120">
      <template #default="scope">
        {{ musicTypeMap[scope.row.musicTypeId] || "未知类型" }}
      </template>
    </el-table-column>
    <el-table-column label="状态" width="100">
      <template #default="scope">
        <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
          {{ scope.row.status === '1' ? '上架' : '下架' }}
        </el-tag>
      </template>
    </el-table-column>
  </el-table>
  <template #footer>
    <el-button @click="showAddMusicDialog = false">取消</el-button>
    <el-button 
      type="primary" 
      @click="handleAddMusicToPlaylist"
      :disabled="!selectedMusicId"
    >
      确定
    </el-button>
  </template>
</el-dialog>
</template>

<style lang="scss">
.icon {
  fill: currentColor;
  width: 20px;
  margin-right: 6px;
}
.input-grey {
  .el-input__wrapper {
    background: #f9f9f9;
    padding-left: 8px;
  }
  .el-select__wrapper {
    background: #f9f9f9;
  }
}
.el-table__header-wrapper {
  border-radius: 6px;
}
.table-header {
  background: #b88b7a !important;
  color: white;
  height: 50px !important;
  font-size: 15px;
  .el-table__cell {
    background: transparent !important;
    font-weight: 500;
  }
}
</style>